#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;

const int MaxN = 1001;
const int MaxM = 1001;
const int MaxNM = MaxN * MaxM;

int n, m;
int dist[MaxNM], que[MaxNM];
char map[MaxN][MaxM];

inline int Pos2Id(pair<int, int> pos) {
	return pos.first * m + pos.second;
}

inline pair<int, int> Id2Pos(int id) {
	   return make_pair(id / m, id % m);
}

int dir[4][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} };

bool IsVaild(pair<int, int> pos){
	 return pos.first >= 0 && pos.first < n && pos.second >=0 && pos.second < m;	
}

void FloodFill(int x, int y, int d) {
	que[0] = Pos2Id(make_pair(x, y));
	dist[Pos2Id(make_pair(x, y))] = d;
	for(int head = 0, tail = 1; head < tail; head++) {
		pair<int,int> now = Id2Pos(que[head]);
		
		for(int i = 0; i < 4; i++){
			pair<int, int> next(now.first + dir[i][0], now.second + dir[i][1]);
			int next_id = Pos2Id(next); 
			
			if(IsVaild(next) && dist[next_id] == -1 && map[next.first][next.second] == '.') {
				//cout << next.first << ' ' << next.second << endl;
				que[tail++] = next_id;
				dist[next_id] = d;
			} 
		}
	}
}

int BFS() {
	int head = 0, tail = 0;
	
	for(int id = 0; id < n * m; id++){
		if(dist[id] == 0){
			que[tail++] = id;
		}
	}
	
	for(; head < tail; head++) {
		pair<int,int> now = Id2Pos(que[head]);
		
		for(int i = 0; i < 4; i++){
			pair<int, int> next(now.first + dir[i][0], now.second + dir[i][1]);
			int next_id = Pos2Id(next); 
			
			if(IsVaild(next)) {
				if(dist[next_id] == -1) {
					que[tail++] = next_id;
					dist[next_id] = dist[que[head]] + 1;
				}
				else if(dist[next_id] == MaxNM) {
					return dist[que[head]];
				}
			}
		}
	}
	return -1;
}

int main() {
	int T;
	
	cin >> T;
	
	while(T--){
		cin >> n >> m;
		
		memset(dist, -1, sizeof(int) * n * m);
		for(int i = 0; i < n; i++)
			scanf("%s", map[i]);
		FloodFill(0, 0, 0);
		if(dist[Pos2Id(make_pair(n - 1, m - 1))] == -1){
			FloodFill(n - 1, m - 1, MaxNM);
			printf("%d\n", BFS());
		}
		else{
			printf("0\n");
		} 
	}	
} 
